<template>
  <div class="execution">
    <basic-container>
      <avue-crud
        v-bind="bindVal"
        v-on="onEvent"
        :page.sync="page"
        :permission="permissionList">
        <template slot-scope="scope" slot="menuLeft">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="small"
            v-permission="permissionList.addBtn"
            @click.stop="myAdd()"
          >添 加</el-button>
          <el-button
            type="primary"
            icon="el-icon-submit"
            size="small"
            v-permission="permissionList.submitBtn"
            @click.stop="handleBatchSubmit()"
          >提交</el-button>
	  <el-button    type="primary"   v-if="false"    size="small"       @click="delBatchs()" > 高级删除  </el-button>
          <el-button
            type="primary"
            size="small"
            @click.stop="handleExport()"
          >导 出</el-button>
          <el-button
            type="primary"
            icon="el-icon-press"
            size="small"
            :hidden="true"
            v-if="false"
            @click.stop="handlePrint()"
          >打 印</el-button>
        </template>
        <template slot-scope="scope" slot="menu">
          <el-button
            type="text"
            size="small"
            icon="el-icon-edit"
            v-permission="permissionList.editBtn"
            v-if="scope.row.checkStatus=='0'||scope.row.checkStatus=='3'"
            @click.stop="MyEdit(scope.row,scope.index)"
          >编 辑</el-button>
          <el-button
            type="text"
            size="small"
            icon="el-icon-chat-dot-square"
            v-permission="permissionList.auditBtn"
            v-if="scope.row.checkStatus=='1'"
            @click.stop="myAudit(scope.row,scope.index)"
          >审核</el-button>
          <el-button
            type="text"
            size="small"
            icon="el-icon-view"
            @click.stop="myView(scope.row,scope.index)"
          >预览</el-button>
          <!-- <el-button
            type="text"
            size="small"
            icon="el-icon-delete"
            v-if="scope.row.checkStatus=='0'"
            v-permission="permissionList.delBtn"
            @click.stop="rowDel(scope.row,scope.index)"
          >删除</el-button> -->
	  <el-button
            type="text"
            size="small"
            icon="el-icon-delete"
            v-if="true"
            v-permission="scope.row.checkStatus=='0' || permissionList.delBtn"
            @click.stop="rowDel(scope.row,scope.index)"
          >删除</el-button>
        </template>
      </avue-crud>
    </basic-container>

    <open-dialog :DialogVisible.sync="addVisableDialog" title="新增" width="80%">
      <el-form label-width="60px">
        <avue-form ref="formAdd" v-model="form" :option="formOptionAdd" style="margin-bottom:20px;"></avue-form>
        <dynamic-crud
          title="计划时间(月)"
          :data="tableDataPlan"
          :option="planOptionAdd"
          :spanMethod="spanMethod1"
          :button="false"
        ></dynamic-crud>
        <div class="bottom-menu-st-plan">
          <el-button type="primary" @click="save">保存</el-button>
          <el-button @click="addVisableDialog=false">取消</el-button>
        </div>
      </el-form>
    </open-dialog>

    <open-dialog :DialogVisible.sync="editVisableDialog" title="编辑" width="80%">
      <el-form label-width="60px">
        <avue-form v-model="form" :option="formOptionAdd" style="margin-bottom:20px;"></avue-form>
        <dynamic-crud
          title="计划时间(月)"
          :button="false"
          :data="tableDataPlan"
          :option="planOptionAdd"
          :spanMethod="spanMethod1">
        </dynamic-crud>
        <div class="bottom-menu-st-plan">
          <el-button type="primary" @click="edit">保存</el-button>
          <el-button @click="editVisableDialog=false">取消</el-button>
        </div>
      </el-form>
    </open-dialog>

    <open-dialog :DialogVisible.sync="auditVisableDialog" title="审核" width="80%">
      <el-form label-width="60px">
        <avue-form v-model="form" :option="formOptionView" :disabled="true" style="margin-bottom:20px;"></avue-form>
        <dynamic-crud title="计划时间(月)" :data="tableDataPlan" :button="false"
          :option="planOptionAdd" :spanMethod="spanMethod1"></dynamic-crud>
        <el-form label-width="110px" style="margin-top: 20px;">
          <el-form-item label="审批建议:">
            <avue-input v-model="form.checkSuggest" type="textarea" :autosize="{ minRows: 4, maxRows: 6}"></avue-input>
          </el-form-item>
        </el-form>
        <div class="bottom-menu-st-plan">
          <el-button type="primary" @click="audit(2)">审批通过</el-button>
          <el-button type="primary" @click="audit(3)">审批不通过</el-button>
          <el-button @click="auditVisableDialog=false">取消</el-button>
        </div>
      </el-form>
    </open-dialog>
    <open-dialog :DialogVisible.sync="viewVisableDialog" title="预览" width="80%">
      <el-form label-width="40px">
        <avue-form v-model="form" :option="formOptionView" style="margin-bottom:20px;"></avue-form>
        <dynamic-crud title="计划时间(月)" :disabled="true" :data="tableDataPlan"
          :option="planOptionAdd" :spanMethod="spanMethod1"></dynamic-crud>
        <avue-form v-if="form.checkStatus!='0'" v-model="formView" :option="formOptionCheckInfo" style="margin-top:40px;margin-bottom:40px;"></avue-form>
        <div class="bottom-menu-st-plan">
          <el-button type="primary" @click="viewVisableDialog=false">取消</el-button>
        </div>
      </el-form>
    </open-dialog>
  </div>
</template>

<script>
import baseCrud from '@/mixins/base-crud'
import {getDetail} from '@/api/subway/swstplanyear'
import {
  auditObj,delBatchs
} from "@/api/subway/swstplanyear";
import {
  planOptionAdd,
  formOptionAdd,
  formOptionView,
  formOptionCheckInfo,nowYear
} from "@/const/crud/subway/swstplanyear";

export default {
  name: "StPlanYear",
  mixins: [baseCrud('subway/swstplanyear')],
  data() {
    return {
      exportName: '年计划列表.xlsx',
      planOptionAdd: planOptionAdd,
      addVisableDialog: false,
      editVisableDialog: false,
      viewVisableDialog: false,
      auditVisableDialog: false,
      formOptionAdd: formOptionAdd,
      formOptionView: formOptionView,
      formOptionCheckInfo: formOptionCheckInfo,
      tableDataPlan: [],
      formAdd: {},
      formView: {},
      searchForm: {
        planYear: nowYear
      }
    };
  },
  computed: {
    permissionList() {
      return {
        addBtn: this.vaildData(this.permissions.st_plan_year_add, false),
        editBtn: this.vaildData(this.permissions.st_plan_year_update, false),
        delBtn: this.vaildData(this.permissions.st_plan_year_delete, false),
        submitBtn: this.vaildData(this.permissions.st_plan_year_submit, false),
        auditBtn: this.vaildData(this.permissions.st_plan_year_audit, false)
      }
    }
  },
  watch: {
    tableDataPlan: {
      handler(newValue, oldValue){
        let planMonths = this.tableDataToPlan(newValue)
        let total = 0
        planMonths.forEach(p => {
          total += (p.planNumberOld || 0)
        })
        this.form.planNumber = total
      },
      deep: true
    }
  },
  methods: {
    spanMethod1({ row, column, rowIndex, columnIndex }) {
      if (row.cycle != "" && columnIndex > 1){
        if ((columnIndex-2)%Number(row.cycle) == 0) {
          return [1, Number(row.cycle)];
        }else{
          return [0,0]
        }
      }
    },
    save() {
      this.$refs.formAdd.validate(valid => {
        if(valid){
          this.form.planMonths = this.tableDataToPlan(this.tableDataPlan)
          this.rowSave(this.form, () => {
            this.addVisableDialog = false
          }, () => {})
        }
      })
    },
    edit() {
      this.form.planMonths = this.tableDataToPlan(this.tableDataPlan)
      this.rowUpdate(this.form, 0, () => {
        this.editVisableDialog = false
      }, () => {})
    },
    MyEdit(row, index) {
      this.form = row
      getDetail(row.id).then(response => {
        this.tableDataPlan = this.planToTableData(response.data.data)
        this.tableDataPlan.forEach(plan => {
          plan.$cellEdit = true
        })
        this.editVisableDialog = true;
      })
    },
    myAdd() {
      this.tableDataPlan = [{
        $cellEdit: true,
        cycle: '1'
      },{
        $cellEdit: true,
        cycle: '3'
      }]
      this.addVisableDialog = true;
    },
    myView(row) {
      this.form = row
      this.formView = row
      getDetail(row.id).then(response => {
        this.tableDataPlan = this.planToTableData(response.data.data)
        this.viewVisableDialog = true;
      })
    },
    myDel(){
      var item;
      for(const tableItem of this.$refs.crud.tableSelect){
        item = tableItem;
      }
      if(this.$refs.crud.tableSelect.length == 0){
        this.$message.info("请选择要删除的记录");
      }else if(this.item.checkStatus != 2){
        this.$message.error("待审批状态和审批通过状态记录不允许删除！")
      }else{
        this.$confirm('确定删除吗？')
          .then(_ => {
              // var ids = [];
              // for(const id of this.$refs.crud.tableSelect){
              //   ids.push(id.id);
              // }
              // delsObj(ids)
              //   .then((data) => {
              //     this.$message.success("删除成功");
              //     this.getList(this.page);
              //     done();
              //   })
              //   .catch(() => {
              //     loading();
              //   })
          })
          .catch(_ => {
            this.$refs.crud.toggleSelection();
          });
      }
    },
    myAudit(row) {
      this.form = row
      getDetail(row.id).then(response => {
        this.tableDataPlan = this.planToTableData(response.data.data)
        this.auditVisableDialog = true
      })
    },
    beforeRowSave(row, done, loading){
      row.checkStatus = 0;
      done()
    },
    audit(status) {
      if(status==3&&this.validatenull(this.form.checkSuggest)){
        this.$message.info('请输入审批建议')
        return
      }
      this.form.checkStatus = status
      auditObj(this.form).then(() => {
        this.$message.success("审核成功")
        this.auditVisableDialog = false;
        this.getList(this.page)
      });
    },
     //高级删除操作
     delBatchs: function () {
        if (this.$refs.crud.tableSelect.length < 1) {
          this.$message.error("请选择数据！");
          return false;
        }
        let ids = [];
        for (const table of this.$refs.crud.tableSelect) {         
          ids.push(table.id);
        }
        this.$confirm("确认删除?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          delBatch(ids)
            .then((data) => {
              this.$message.success("删除成功");
              this.getList(this.page);
              done();
            })
            .catch(() => {
              loading();
            });
        });
      },
    tableDataToPlan(tableData){
      let i=1
      let planMonths = []
      while(i <= 12){
        if(!this.validatenull(tableData[1][i])){
          let sycle = Number(tableData[1].cycle)
          let j = 0
          let months = []
          while(j < sycle){
            months.push(i+j)
            j++
          }
          planMonths.push({
            workCycle: tableData[1].cycle,
            planMonth: months.join(','),
            planNumberOld: tableData[1][i]
          })
          i = i + sycle
        }else{
          planMonths.push({
            workCycle: tableData[0].cycle,
            planMonth: i,
            planNumberOld: tableData[0][i]
          })
          i = i + 1
        }
      }
      return planMonths
    },
    planToTableData(planMonths){
      let tableData = [{cycle: '1'}, {}]
      for(let plan of planMonths){
        if(plan.workCycle == '1'){
          tableData[0][plan.planMonth] = plan.planNumberOld
        }else{
          tableData[1].cycle = plan.workCycle
          let index = plan.planMonth.split(',')[0]
          tableData[1][index] = plan.planNumberOld
        }
      }
      return tableData
    }
  }
}
</script>
<style lang="scss" scoped>
.header {
  margin: 0 auto;
  width: 99%;
  padding: 5px 10px;
  border: 1px solid #e4e4e4;
  border-bottom: none;
  background-color: #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.bottom-menu-st-plan {
  margin-top: 48px;
  text-align: center;
}
</style>
